import requests
import json
import os
from random import choice
from urllib.parse import quote
import datetime
import random
import urllib.request
import gzip
import re

'''

'''
configuration = json.load(open("./config.json", encoding='utf-8'))

bot_set = configuration["bot_set"]
music_set = configuration["music_set"]
detect_statement = configuration["detect_statement"]

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.76',
}


# 获取重定向后的网址
def get_redirect_url(url):
    # 请求头，这里我设置了浏览器代理
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
    # 请求网页
    response = requests.get(url, headers=headers)
    print(response.url)  # 打印重定向后的网址
    # 返回重定向后的网址
    return response.url


# 帮助菜单
def help_menu(msg):
    if msg in detect_statement["help"]:
        help_base = "这里是帮助菜单：\n"
        help_base += "以下之类在非闲聊状态下均需要@苏苏\n"
        # help_base += "1.私聊调教对话 例如aaa+bbb \n"
        # help_base += "      那么发送aaa就会返回bbb啦~\n"
        # help_base += "      可以发送rmaaa+bbb删除对话哦~\n"
        help_base += "2.@苏苏并说[ " + "|".join(detect_statement["chat_group_open"]) + " ]会激活聊天机器人聊天\n"
        help_base += "      @苏苏并说[ " + "|".join(detect_statement["chat_group_stop"]) + " ]会关闭聊天机器人聊天\n"
        help_base += "      私聊是[ " + "|".join(detect_statement["chat_private_open"]) + " ]会激活聊天机器人聊天\n"
        help_base += "      私聊是[ " + "|".join(detect_statement["chat_private_stop"]) + " ]会关闭聊天机器人聊天\n"
        # help_base += "3.发送这几个内容之一会获得一张涩图 [ " + "|".join(detect_statement["ghs_pic"]) + " ]\n"
        # help_base += "注1：群内涩图和私聊涩图不同 \n"
        # help_base += "注2：结尾+choice 图片名 可发送指定图片 \n"
        help_base += "4.发送这几个内容之一会返回一句古诗 [ " + "|".join(detect_statement["gu_shi"]) + " ]\n"
        help_base += "5.发送这几个内容之一会返回一句舔狗日记 [ " + "|".join(detect_statement["get_dog"]) + " ]\n"
        help_base += "6.发送这几个内容之一会返回一张二次元图片 [ " + "|".join(detect_statement["api_pic"]) + " ]\n"
        # help_base += "注：结尾加 choice n 可选择使用哪一个api n为你api数量-1 \n"
        help_base += "7.发送这几个内容之一会返回一张mao_pic文件夹内的图片 [ " + "|".join(detect_statement["mao_pic"]) + " ]\n"
        help_base += "8.发送这几个内容之一会返回或者分享一首歌 [ " + "|".join(detect_statement["get_music"]) + " ]\n"
        help_base += "9.发送这几个内容之一会返回当前时间 [ " + "|".join(detect_statement["get_time"]) + " ]\n"
        help_base += "10.发送 地点+[ " + "|".join(detect_statement["get_weather"]) + " ] 返回天气\n"
        help_base += "11.发送 [时间（例：3点10分 或3点 ps:没分也行）]+[" + "|".join(configuration["remind"]["key_word"]) + "]+[要干啥]到了时间苏苏会@你\n"
        # help_base += "12.发送 +[" + "|".join(detect_statement["get_lsp"]) + "]+苏苏会@群色匹\n"
        help_base += "13.私聊发送 每天[x点|x点x|x点x分]提醒我天气 会每天固定时间提醒\n"
        help_base += "14.发送这几个内容之一会返回一个笑话 [ " + "|".join(detect_statement["get_joke"]) + " ]\n"
        help_base += "15.发送这几个内容之一会返回一句土味情话 [ " + "|".join(detect_statement["get_lovewords"]) + " ]\n"
        help_base += "15.发送这几个内容之一会返回一张修勾图片 [ " + "|".join(detect_statement["get_dog_pic"]) + " ]\n"
        help_base += "另外，如果你说了不改说的话会根据管理员的设置撤回消息或者封禁60s\n"
        print(help_base)
        return [True, help_base]
    return [False]


'''
原作者的api是从p站搞涩图，经常请求不到
原本想建个api的，但是涩图太色了，改本地了
然后我想了想应该分个级
    ghs_pic 涩图是那种没有什么漏点的不是特别色的，默认的直接发群里
    hs_pic 黄色是那种比较涩的，只能私聊获得
'''


def get_time(msg):
    if msg in detect_statement["get_time"]:
        curr_time = datetime.datetime.now()
        res = "现在是" + str(curr_time.year) + "年" + str(curr_time.month) + "月" + str(curr_time.day) + "日 \n" + str(
            curr_time.hour) + "点" + str(curr_time.minute) + "分"
        return [True, res]
    return [False]


def ghs_pic(msg):
    for key in detect_statement["ghs_pic"]:
        if key in msg:
            if "choice " in msg:
                ind = msg.index('choice ')
                ret = msg[ind+7:]
                print(ret)
                local_img_url = "[CQ:image,file=file:///" + bot_set["ghs_pic_path"] + ret + "]"
            else:
                setu_list = os.listdir(bot_set["ghs_pic_path"])
                local_img_url = "[CQ:image,file=file:///" + bot_set["ghs_pic_path"] + choice(setu_list) + "]"
            return [True, local_img_url]
        return [False]


def hs_pic(msg):
    for key in detect_statement["ghs_pic"]:
        if key in msg:
            if "choice " in msg:
                ind = msg.index('choice ')
                ret = msg[ind+7:]
                print(ret)
                local_img_url = "[CQ:image,file=file:///" + bot_set["hs_pic_path"] + ret + "]"
            else:
                setu_list = os.listdir(bot_set["ghs_pic_path"])
                local_img_url = "[CQ:image,file=file:///" + bot_set["hs_pic_path"] + choice(setu_list) + "]"
            return [True, local_img_url]
        return [False]


def get_lsp(msg, who_is_lsp):
    if msg in detect_statement["get_lsp"]:
        res = max(who_is_lsp, key=lambda x: who_is_lsp[x])
        return [True, "[CQ:at,qq={}]".format(res) + " 找到你了，哈哈哈哈"]
    return [False]


def mao_pic(msg):
    if msg in detect_statement["mao_pic"]:
        url = 'https://api.thecatapi.com/v1/images/search?limit=1'  # 获取用户输入的城市进行查询
        resp = requests.get(url, headers=headers).text
        cat_url = json.loads(resp)[0]['url']
        content = requests.get(cat_url, headers=headers).content
        name = cat_url.split('/')[-1]
        with open(f'{bot_set["cat_path"]}' + name, 'wb') as f:
            f.write(content)
        local_img_url = "[CQ:image,file=file:///" + bot_set["cat_path"] + name + "]"
        return [True, local_img_url]
    else:
        return [False]


# 古诗 ，来自今日诗词api
def gu_shi(msg):
    if msg in detect_statement["gu_shi"]:
        try:
            req_url = "https://v1.jinrishici.com/rensheng.txt"
            res = requests.get(req_url)
            print(res.text)
            return [True, res.text]
        except Exception as e:
            print(e)
            return [False, "阿这，出了一点问题"]
    return [False]


# 舔狗日记 ，来自今小歪api
def get_dog(msg):
    if msg in detect_statement["get_dog"]:
        try:
            req_url = "https://api.aixiaowai.cn/ylapi/index.php/?code=js"
            print("get_dog请求数据 ...")
            resp = requests.get(req_url,headers=headers)
            content = resp.text
            #print(content)
            match = re.search(r'document\.write\("(.*?)"\);', content)
            if match:
                rev = match.group(1)
                return [True, rev]
            else:
                return [False,"未找到document.write中的内容"]
        except Exception as e:
            return [False, f"get_dog请求数据失败,{e}"]
    return [False]


# 通过请求api获取图片
def api_pic(msg):
    for key in detect_statement["api_pic"]:
        if key in msg:
            print(msg)
            try:
                urls = configuration["botUrls"]
                if "choice " in msg :
                    ind = msg.index('choice ')
                    ret = int(msg[ind + 7])
                    print(ret)
                else:
                    ret = random.randint(0, len(urls)-1)
                res = get_redirect_url(urls[ret])
                local_img_url = "[CQ:image,file=" + res + "]"
                return [True, local_img_url]
            except Exception as e:
                print(e)
                return [False, "阿这，出了一点问题"]
        return [False]


# def weather(place):
#     url1 = 'http://wthrcdn.etouch.cn/weather_mini?city=' + urllib.parse.quote(place)
#     weather_data = urllib.request.urlopen(url1).read()
#     weather_data = gzip.decompress(weather_data).decode('utf-8')
#     weather_dict = json.loads(weather_data)
#     if weather_dict.get('desc') == 'invilad-citykey':
#         res = '你输入的城市名有误，或者天气中心未收录你所在城市，不过八成是你输入的格式错了'
#         return [True, res]
#     elif weather_dict.get('desc') == 'OK':
#         forecast = weather_dict.get('data').get('forecast')
#         res = "------天气查询------ \n"
#         res += "城市：" + weather_dict.get('data').get('city') + " \n"
#         res += "温度：" + weather_dict.get('data').get('wendu') + "℃ " + " \n"
#         res += "感冒：" + weather_dict.get('data').get('ganmao') + " \n"
#         res += "风向：" + forecast[0].get('fengxiang') + " \n"
#         res += "风级：" + forecast[0].get('fengli') + " \n"
#         res += "高温：" + forecast[0].get('high') + " \n"
#         res += "低温：" + forecast[0].get('low') + " \n"
#         res += "天气：" + forecast[0].get('type') + " \n"
#         res += "日期：" + forecast[0].get('date') + " \n"
#         res += "*******************************" + " \n"
#         for i in range(1, 5):
#             res += '日期：' + forecast[i].get('date') + " \n"
#             res += '风向：' + forecast[i].get('fengxiang') + " \n"
#             res += '风级：' + forecast[i].get('fengli') + " \n"
#             res += '高温：' + forecast[i].get('high') + " \n"
#             res += '低温：' + forecast[i].get('low') + " \n"
#             res += '天气：' + forecast[i].get('type') + " \n"
#             res += '--------------------------' + " \n"
#         return [True, res]
#     return [False]

def get_city_code(city_name):
    # 构造API请求的URL
    base_url = 'https://geoapi.heweather.net/v2/city/lookup'
    params = {
        'location': city_name,
        'key': '504c9d851d174eefb0e53f88df94a64d',
    }

    try:
        # 发送API请求
        response = requests.get(base_url, params=params)
        data = response.json()

        # 解析API响应
        if data.get('code') == '200':
            city_info = data.get('location')
            if city_info:
                # 返回城市编码
                return city_info[0].get('id')
            else:
                return [False,'未找到匹配的城市编码。']
        else:
            return [False,'查询城市编码失败，请检查API密钥或城市名称。']
    except Exception as e:
        return [False,f'发生错误：{str(e)}']

def get_weather(msg):
    try:
        for weather_key in detect_statement["get_weather"]:
            if msg[-len(weather_key):] == weather_key:#判断结束语是不是关键词
                city = msg[:-len(weather_key)]#城市名
                #print(city)
                api_key = '504c9d851d174eefb0e53f88df94a64d'
                # 构造API请求的URL
                base_url = 'https://devapi.qweather.com/v7/weather/now'
                params = {
                    'location': get_city_code(city) ,
                    'key': api_key,
                }
                try:
                    # 发送API请求
                    response = requests.get(base_url, params=params,headers=headers)
                    data = response.json()
                    #print(data)
                    # 解析API响应
                    if data['code'] == '200':
                        weather_info = data['now']['text']
                        temperature = data['now']['temp']
                        winDir = data['now']['windDir']
                        return [True,f'城市：{city}\n天气：{weather_info}\n温度：{temperature}°C\n风向：{winDir}']
                    else:
                        return [False,'查询天气失败，请检查城市名称或API密钥。']
                except Exception as e:
                    return [False,f'发生错误：{str(e)}']
    except:
        return [False]

    return [False]

def get_music(msg):
    if msg in detect_statement["get_music"]:
        music_file_link = music_set["music_file_link"]
        if music_file_link is 0:
            try:
                req_url = "https://api.paugram.com/acgm/?list=1&play=true"
                res = get_redirect_url(req_url)
                print(res)
                return [True, res]
            except Exception as e:
                print(e)
                return [False, "阿这，出了一点问题"]
        elif music_file_link is 1:
            # [CQ:music,type=163,id=28949129]
            res = "[CQ:music,type=" + music_set["music_type"] + ",id=" + choice(music_set["musics"]) + "]"
            return [True, res]
    return [False]


def send_forward(msg, group_id, ws, sender):
    group_msg = []
    for item in msg:
        each_msg = {
            "type": "node",
            "data": {
                "name": "呜啦",
                "uin": bot_set["self_qq"],
                "content": item
            }
        }
        group_msg.append(each_msg)
    data = {
        'group_id': group_id,
        'messages': group_msg
    }
    # print(data)
    # cq_url = "ws://127.0.0.1:5700/send_group_forward_msg"
    # rev3 = requests.post(cq_url,data=data)
    # print(rev3.json())
    action = "send_group_forward_msg"
    post_data = json.dumps({"action": action, "params": data})
    rev = ws.send(post_data)
    # print(rev)
    returnStr = "[CQ:at,qq={sender}]".format(sender=sender)
    return returnStr


def send_private(msg, sender, ws):
    data = {
        'user_id': sender,
        'message': msg,
        'auto_escape': False
    }
    # cq_url = "ws://127.0.0.1:5700/send_private_msg"
    action = "send_private_msg"
    post_data = json.dumps({"action": action, "params": data})
    rev = ws.send(post_data)
    return rev


def add_friend(sender, msg, ws):
    # if sender in admin_qq:
    #     return [True, '']
    try:
        print('add_friends')
        if msg == 'Alice':
            return [True, ""]
        else:
            return [False, ""]
        # print(result)
        # if result != ():
        #     return [True, ""]
    except Exception as e:
        print(e)
    return [False, '']

def get_joke(msg):
    if msg in detect_statement["get_joke"]:
        url=f'http://api.qingyunke.com/api.php?key=free&appid=0&msg=笑话'
        resp = requests.get(url,headers=headers).text
        content = json.loads(resp)
        rev=content['content'].replace('{br}',' ').strip('').replace("菲菲",'苏苏')
        return [True,rev]

    else:
        return [False]

def get_category_jokes(msg):
    if msg in detect_statement["get_category_jokes"]:
        url='http://api.qingyunke.com/api.php?key=free&appid=0&msg=笑话分类'
        resp = requests.get(url,headers=headers).text
        content = json.loads(resp)
        rev=content['content'].replace('{br}',' ').replace("菲菲",'苏苏')
        return [True,rev]

    else:
        return [False]

def get_category_joke(msg):
    if msg in detect_statement["get_category_joke"]:
        url=f'http://api.qingyunke.com/api.php?key=free&appid=0&msg={msg}'
        resp = requests.get(url,headers=headers).text
        content = json.loads(resp)
        rev=content['content'].replace('{br}',' ').replace("菲菲",'苏苏')
        return [True,rev]
    else:
        return [False]

def get_lovewords(msg):
    if msg in detect_statement["get_lovewords"]:
        url = 'https://api.uomg.com/api/rand.qinghua?format=json'  # 获取用户输入的城市进行查询
        resp = requests.get(url, headers=headers).text
        #print(resp)
        content = json.loads(resp)['content']
        rev = content
        return [True,rev]
    else:
        return [False]

def get_dog_pic(msg):
    if msg in detect_statement["get_dog_pic"]:
        url = 'https://dog.ceo/api/breeds/image/random'  # 获取用户输入的城市进行查询
        resp = requests.get(url, headers=headers).text
        dog_url = json.loads(resp)['message']
        content = requests.get(dog_url,headers=headers).content
        name = dog_url.split('/')[-1]
        with open(f'{bot_set["dog_path"]}'+name,'wb')as f:
            f.write(content)
        local_img_url = "[CQ:image,file=file:///" + bot_set["dog_path"] + name + "]"
        return [True,local_img_url]
    else:
        return [False]

def get_fortune(msg,user_id):
    if msg in detect_statement["get_fortune"]:
        url = f'https://api.fanlisky.cn/api/qr-fortune/get/{user_id}'  # 获取用户输入的城市进行查询
        resp = requests.get(url, headers=headers).text
        # print(resp)
        resp = json.loads(resp)
        fortuneSummary = resp['data']['fortuneSummary']
        luckyStar = resp['data']['luckyStar']
        signText = resp['data']['signText']
        unSignText = resp['data']['unSignText']
        rev = "幸运度：" + fortuneSummary + '\n' + "幸运星指数：" + luckyStar + '\n' + "卦象：" + signText + '\n' + unSignText
        return [True,rev]
    else:
        return [False]


def main():
    print(get_fortune("运势",123456))

if __name__ == '__main__':
    main()